# koroFileHeader at Yungoal acer
# Create: 2022-10-08 13:58:27
# LastEdit: 2022-11-14 09:49:29
"""报告API"""
__author__ = '749B'

import datetime
import requests
import urllib.parse

from django.utils import dateparse

from typing import List, Optional

class AzureBillingClient(object):

    base_url = 'https://ea.azure.cn'

    def __init__(self, enrollment: str, access_key: str, api_version: str = '2014-09-02', name: str = '') -> None:
        self.enrollment = enrollment
        self._headers = {
            'api-version': api_version,
            'Authorization': f'bearer {access_key}',
        }
        self.name = name

    def get_usage_list(self) -> requests.Response:
        uri = f'/rest/{self.enrollment}/usage-reports'
        url = urllib.parse.urljoin(self.base_url, uri)
        r = requests.get(url, headers=self._headers)
        r.raise_for_status()
        return r

    def get_available_months(self) -> List[datetime.date]:
        r = self.get_usage_list()
        o = r.json()
        months = [ dateparse.parse_date(m['Month'] + '-01') for m in o['AvailableMonths'] ]
        months.sort()
        return months

    def get_usage_by_month(self, month_str: str, report_type: Optional[str]=None, fmt: Optional[str]=None) -> requests.Response:
        report_type = report_type.lower() if report_type else 'detail'
        assert report_type in ['summary', 'detail', 'storecharge', 'pricesheet']
        fmt = fmt.lower() if fmt else 'json'
        # 注意 json 格式输出的记录是乱序的和 csv 不同
        assert fmt in ['csv', 'json']

        base_uri = f'/rest/{self.enrollment}/usage-report'
        query = {
            'month': month_str,
            'type': report_type,
            'fmt': fmt
        }
        params = urllib.parse.urlencode(query)
        uri = f'{base_uri}?{params}'
        url = urllib.parse.urljoin(self.base_url, uri)
        r = requests.get(url, headers=self._headers)
        r.raise_for_status()
        r.encoding = 'utf-8-sig'
        return r
    
    def get_paginated_usage_by_month(self, month_str: str, fmt: Optional[str]=None, page_index: int=0) -> requests.Response:
        fmt = fmt.lower() if fmt else 'json'
        assert fmt in ['csv', 'json']

        base_uri = f'/rest/{self.enrollment}/usage-report/paginated'
        query = {
            'month': month_str,
            'fmt': fmt,
            'pageindex': page_index,
        }
        params = urllib.parse.urlencode(query)
        uri = f'{base_uri}?{params}'
        url = urllib.parse.urljoin(self.base_url, uri)
        r = requests.get(url, headers=self._headers)
        r.raise_for_status()
        r.encoding = 'utf-8-sig'
        return r

